package com.combetter.changxing.viewmodel;

import android.Manifest;
import android.app.Application;
import android.content.Context;
import android.databinding.ObservableField;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.combetter.changxing.Config;
import com.combetter.changxing.MyApp;
import com.combetter.changxing.R;
import com.combetter.changxing.constanst.Constants;
import com.combetter.changxing.db.entity.User;
import com.combetter.changxing.model.EventMessage;
import com.combetter.changxing.model.Image;
import com.combetter.changxing.model.parameter.RegisterParameter;
import com.combetter.changxing.net.service.APIService;
import com.combetter.changxing.ui.activity.MineUserInfoActivity;
import com.combetter.changxing.ui.dialog.AvatarSelectDialog;
import com.combetter.changxing.ui.dialog.BelowSelectDialog;
import com.combetter.changxing.ui.dialog.CityListDialog;
import com.combetter.changxing.ui.dialog.LoadingDialog;
import com.combetter.changxing.ui.fragment.MineAlterPhoneFragment;
import com.combetter.changxing.ui.fragment.MineAlterPwdFragment;
import com.combetter.changxing.ui.fragment.MineUserInfoFragment;
import com.combetter.changxing.util.Check;
import com.combetter.changxing.util.FileUtils;
import com.combetter.changxing.util.FragmentUtils;
import com.combetter.changxing.util.LogUtil;
import com.combetter.changxing.util.RegUtils;
import com.combetter.changxing.util.RxUtil;
import com.combetter.changxing.util.ToastUtils;
import com.combetter.changxing.viewmodel.base.BaseViewModel;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import static com.combetter.changxing.constanst.Constants.REUEST_CODDE;

/**
 * Created by 深圳唐龙飞讯科技有限公司 on 2018/6/13.
 */
public class MineUserInfoViewModel extends BaseViewModel {
    //性别Id
    public static int sexId = 4;
    //年龄Id
    public static int ageId = 5;

    //绑定的手机号
    public ObservableField<String> formerPhone = new ObservableField<>("");

    public ObservableField<String> code = new ObservableField<>("");
    //新手机号
    public ObservableField<String> newPhone = new ObservableField<>("");

    //原来密码
    public ObservableField<String> formerPwd = new ObservableField<>("");
    //新密码
    public ObservableField<String> newPwd = new ObservableField<>("");
    //重复输入新密码
    public ObservableField<String> newPwd2 = new ObservableField<>("");
    //头像url
    public ObservableField<String> url = new ObservableField<>("");


    private User user;

    public MineUserInfoViewModel(@NonNull Application application) {
        super(application);
    }

    public void back(View view) {
        Fragment fragment = FragmentUtils.getTopShowFragment(((MineUserInfoActivity) view.getContext()).getSupportFragmentManager());
        if (fragment.getClass().getSimpleName().equals(MineUserInfoFragment.class.getSimpleName())) {
            ((MineUserInfoActivity) view.getContext()).finish();
        } else {
            ((MineUserInfoActivity) view.getContext()).setTitle("修改资料");
            FragmentUtils.popFragment(((MineUserInfoActivity) view.getContext()).getSupportFragmentManager());
        }
    }

    /**
     * 修改头像
     *
     * @param context
     * @param file
     */
    public void updateHead(Context context, File file) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part avatar = MultipartBody.Part.createFormData("uploadFile", file.getName(), requestBody);
        LoadingDialog dialog = LoadingDialog.getInstance(context);
        dialog.show();
        mHttpRequest.createService(APIService.class)
                .fileUpload(avatar)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnError(throwable -> dialog.dismiss())
                .subscribe(imageHttpResult -> {
                    LogUtil.e("上传文件返回：" + new Gson().toJson(imageHttpResult));
                    PictureFileUtils.deleteCacheDirFile(context);

                    if (FileUtils.cleanInternalCache(context)) {
                        LogUtil.e("file.getPath() 删除成功  ");
                    } else {
                        LogUtil.e("file.getPath() 删除失败  ");
                    }

                    dialog.dismiss();
                    if (imageHttpResult.getCode() == 200) {
                        RegisterParameter parameter = new RegisterParameter();
                        Image image = imageHttpResult.getData();
                        parameter.setSubImages(Config.URL_BASE + image.getImgPath());
                        alterInfo(context, parameter);
                    } else {
                        ToastUtils.error(imageHttpResult.getMsg());
                    }
                });
    }

    public void onClick(View view) {
        switch (view.getId()) {
            /**
             * 修改登录密码
             */
            case R.id.alter_layout:
                ((MineUserInfoActivity) view.getContext()).setTitle("修改密码");
                FragmentUtils.replaceFragment(((MineUserInfoActivity) view.getContext()).getSupportFragmentManager(), R.id.info_layout, new MineAlterPwdFragment(), true);
                break;
            /**
             * 修改手机号
             */
            case R.id.phone_layout:
                ((MineUserInfoActivity) view.getContext()).setTitle("修改手机号");
                FragmentUtils.replaceFragment(((MineUserInfoActivity) view.getContext()).getSupportFragmentManager(), R.id.info_layout, new MineAlterPhoneFragment(), true);
                break;

            /**
             * 修改地址
             */
            case R.id.rl_location:
                startCityList(view);
                break;


            /**
             * 修改头像
             */
            case R.id.head_layout:
                RxPermissions rxPermissions = new RxPermissions(((MineUserInfoActivity) view.getContext()));
                rxPermissions.request(Manifest.permission.CAMERA).subscribe(aBoolean -> {
                    if (aBoolean) {
                        showAvatarSelectDialog(view);
                    } else {
                        ToastUtils.error("没有开启相机权限");
                    }
                });
                break;


        }
    }

    /**
     * 性别
     *
     * @param view
     */
    public void setSex(View view) {
        ArrayList<String> list = new ArrayList<>();
        list.add("男");
        list.add("女");
        BelowSelectDialog dialog = new BelowSelectDialog();
        Bundle bundle = new Bundle();
        bundle.putStringArrayList("mOptionsItems", list);
        bundle.putInt("titleId", sexId);
        dialog.setArguments(bundle);
        Fragment fragment = FragmentUtils.getTopShowFragment(((MineUserInfoActivity) view.getContext()).getSupportFragmentManager());
        dialog.setTargetFragment(fragment, REUEST_CODDE);
        dialog.show(((MineUserInfoActivity) view.getContext()).getSupportFragmentManager(), "");
    }

    /**
     * 年龄
     *
     * @param view
     */
    public void setAge(View view) {
        ArrayList<String> list = new ArrayList<>();
        for (int i = 18; i < 101; i++) {
            list.add(i + "");
        }
        BelowSelectDialog dialog = new BelowSelectDialog();
        Bundle bundle = new Bundle();
        bundle.putStringArrayList("mOptionsItems", list);
        bundle.putInt("titleId", ageId);
        dialog.setArguments(bundle);
        Fragment fragment = FragmentUtils.getTopShowFragment(((MineUserInfoActivity) view.getContext()).getSupportFragmentManager());
        dialog.setTargetFragment(fragment, REUEST_CODDE);
        dialog.show(((MineUserInfoActivity) view.getContext()).getSupportFragmentManager(), "");
    }


    /**
     * 自定义dialog
     */
    public void showAvatarSelectDialog(View view) {
        final AvatarSelectDialog avatarSelectDialog = new AvatarSelectDialog();
        Bundle bundle = new Bundle();
        bundle.putInt(Constants.AVATAR_SELECT, 0);
        avatarSelectDialog.setArguments(bundle);
        avatarSelectDialog.setOnAvatarItemClickListener(new AvatarSelectDialog.OnAvatarItemClickListener() {
            @Override
            public void onTakePhotoClick() {//拍照
                showCameraAction(view);
                avatarSelectDialog.dismiss();
            }

            @Override
            public void onPhotoAlbumClick() {//相册
                showPhotoAlbum(view);
                avatarSelectDialog.dismiss();
            }
        });
        avatarSelectDialog.show(((MineUserInfoActivity) view.getContext()).getSupportFragmentManager(), "AvatarSelectDialog");
    }


    /**
     * 打开相机
     */
    public void showCameraAction(View view) {
        PictureSelector.create(FragmentUtils.getTopShowFragment(((MineUserInfoActivity) view.getContext()).getSupportFragmentManager()))
                .openCamera(PictureMimeType.ofImage())
                .theme(R.style.picture_default_style)
                .maxSelectNum(1)// 最大图片选择数量 int
                .minSelectNum(0)// 最小选择数量 int
                .imageSpanCount(4)// 每行显示个数 int
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                .previewImage(true)// 是否可预览图片 true or false
                .isCamera(false)// 是否显示拍照按钮 true or false
                .enableCrop(true)// 是否裁剪 true or false
                .compress(true)// 是否压缩 true or false
                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
                .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
                .showCropGrid(true)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                .rotateEnabled(true) // 裁剪是否可旋转图片 true or false
                .scaleEnabled(true)// 裁剪是否可放大缩小图片 true or false
                .withAspectRatio(1, 1)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    /**
     * 打开相册
     */
    public void showPhotoAlbum(View view) {
        PictureSelector.create(FragmentUtils.getTopShowFragment(((MineUserInfoActivity) view.getContext()).getSupportFragmentManager()))
                .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()
                .theme(R.style.picture_default_style)
                .maxSelectNum(1)// 最大图片选择数量 int
                .minSelectNum(0)// 最小选择数量 int
                .imageSpanCount(4)// 每行显示个数 int
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                .previewImage(true)// 是否可预览图片 true or false
                .isCamera(false)// 是否显示拍照按钮 true or false
                .enableCrop(true)// 是否裁剪 true or false
                .withAspectRatio(1, 1)
                .compress(true)// 是否压缩 true or false
                .freeStyleCropEnabled(false)// 裁剪框是否可拖拽 true or false
                .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
                .showCropGrid(true)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                .rotateEnabled(true) // 裁剪是否可旋转图片 true or false
                .scaleEnabled(true)// 裁剪是否可放大缩小图片 true or false
                .cropWH(256, 256)
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }


    /**
     * 跳转城市列表dialog
     *
     * @param view
     */
    public void startCityList(View view) {
        CityListDialog dialog = new CityListDialog();
        Fragment fragment = FragmentUtils.getTopShowFragment(((MineUserInfoActivity) view.getContext()).getSupportFragmentManager());
        dialog.setTargetFragment(fragment, REUEST_CODDE);
        dialog.show(((MineUserInfoActivity) view.getContext()).getSupportFragmentManager(), "");
    }

    /**
     * 修改用户资料
     *
     * @param parameter
     */
    public void alterInfo(Context context, RegisterParameter parameter) {
        user = MyApp.getInstance().getUserInfo();
        LoadingDialog dialog = LoadingDialog.getInstance(context);
        dialog.show();
        HashMap<String, String> map = new HashMap<>();
        if (!Check.isEmpty(parameter.getPhone())) {
            map.put("phone", parameter.getPhone());
            user.setPhone(parameter.getPhone());
        } else if (!Check.isEmpty(parameter.getPassword())) {
            map.put("password", parameter.getPassword());
        } else if (!Check.isEmpty(parameter.getSex())) {
            map.put("sex", parameter.getSex());
            user.setSex(parameter.getSex());
        } else if (!Check.isEmpty(parameter.getCity())) {
            map.put("addressName", parameter.getCity());
            user.setAddress_name(parameter.getCity());
        } else if (!Check.isEmpty(parameter.getAge())) {
            map.put("age", parameter.getAge());
            user.setAge(parameter.getAge());
        } else if (!Check.isEmpty(parameter.getSubImages())) {
            map.put("subImages", parameter.getSubImages());
            user.setSubImages(parameter.getSubImages());
            url.set(user.getSubImages());
        }
        map.put("type", "2");
        map.put("uid", user.getUid());
        LogUtil.e("修改资料请求: " + new Gson().toJson(map));
        mHttpRequest.createService(APIService.class)
                .register(map)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .doOnError(throwable -> dialog.dismiss())
                .subscribe(userHttpResult -> {
                    LogUtil.e("修改资料返回：", userHttpResult);
                    dialog.dismiss();
                    if (userHttpResult.getCode() == 200) {
                        ToastUtils.success("修改资料成功");
                        MyApp.getInstance().getDatabase().userDao().insertUser(user);
                        EventBus.getDefault().post(new EventMessage("update", ""));
                    } else {
                        ToastUtils.error(userHttpResult.getMsg());
                    }
                });

    }


    /**
     * 发送验证码
     */
    public void sendCode(View view) {
        TextView sendCode = (TextView) view;
        user = MyApp.getInstance().getUserInfo();
        if (TextUtils.isEmpty(formerPhone.get())) {
            ToastUtils.error("请输入当前绑定手机号");
            return;
        }
        if (!formerPhone.get().equals(user.getPhone())) {
            ToastUtils.error("绑定手机号输入不正确");
            return;
        }
        mHttpRequest.createService(APIService.class)
                .sendCode(user.getPhone(), 3)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(httpResult -> {

                    LogUtil.e("验证码返回：", httpResult);
                    if (httpResult.getCode() == 200) {
                        LogUtil.e("发送验证码成功 " + httpResult.getData());
//                        ToastUtils.success("发送验证码成功: " + httpResult.getData());
//                        savaCode = httpResult.getData().toString();
                        RxUtil.countDown(60).doOnComplete(() -> {
                            sendCode.setEnabled(true);
                            sendCode.setText("发送验证码");
                        }).subscribe(integer -> {
                            sendCode.setEnabled(false);
                            sendCode.setText("(" + integer + ")重新发送");
                        });
                    } else {
                        ToastUtils.error(httpResult.getMsg());
                    }
                });
    }

    /**
     * 修改手机号
     *
     * @param view
     */
    public void alterPhone(View view) {
        if (Check.isEmpty(formerPhone.get())) {
            ToastUtils.error("请输入当前绑定手机号");
            return;
        }
        if (!formerPhone.get().equals(MyApp.getInstance().getUserInfo().getPhone())) {
            ToastUtils.error("绑定手机号输入不正确");
            return;
        }
        if (Check.isEmpty(code.get())) {
            ToastUtils.error("请输入验证码！");
            return;
        }
        if (Check.isEmpty(newPhone.get())) {
            ToastUtils.error("请输入新手机号");
            return;
        }
        if (!RegUtils.isMobile(newPhone.get())) {
            ToastUtils.error("手机号码格式不对！");
            return;
        }

        user = MyApp.getInstance().getUserInfo();
        LoadingDialog dialog = LoadingDialog.getInstance(view.getContext());
        dialog.show();

        HashMap<String, String> map = new HashMap<>();
        map.put("uid", user.getUid());
        map.put("code", code.get());
        map.put("phone", formerPhone.get());
        map.put("newPhone", newPhone.get());
        mHttpRequest.createService(APIService.class)
                .alterPhone(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnError(throwable -> dialog.dismiss())
                .subscribe(httpResult -> {
                    dialog.dismiss();
                    LogUtil.e("修改手机号返回：" + new Gson().toJson(httpResult));
                    if (httpResult.getCode() == 200) {
                        user.setPhone(newPhone.get());
                        MyApp.getInstance().getDatabase().userDao().insertUser(user);
                        back(view);
                    } else {
                        ToastUtils.error(httpResult.getMsg());
                    }
                });
    }


    /**
     * 修改密码
     *
     * @param view
     */
    public void alterPwd(View view) {
        if (Check.isEmpty(formerPwd.get())) {
            ToastUtils.error("请输入原密码");
            return;
        }
        if (Check.isEmpty(newPwd.get())) {
            ToastUtils.error("请输入新密码");
            return;
        }
        if (!newPwd.get().equals(newPwd2.get())) {
            ToastUtils.error("密码不一致");
            return;
        }
        LoadingDialog dialog = LoadingDialog.getInstance(view.getContext());
        dialog.show();

        HashMap<String, String> map = new HashMap<>();
        map.put("uid", MyApp.getInstance().getUserInfo().getUid());
        map.put("old_password", formerPwd.get());
        map.put("password_new", newPwd.get());
        mHttpRequest.createService(APIService.class)
                .resetPassword(map)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .doOnError(throwable -> dialog.dismiss())
                .subscribe(httpResult -> {
                    dialog.dismiss();
                    LogUtil.e("修改密码返回：" + new Gson().toJson(httpResult));
                    if (httpResult.getCode() == 200) {
                        ToastUtils.success("修改密码成功");
                        back(view);
                    } else {
                        ToastUtils.error(httpResult.getMsg());
                    }
                });
    }


}
